package com.scproject.scbef.controller.ImgController;

import com.scproject.scbef.mapper.ImgMapper;
import com.scproject.scbef.pojo.Img;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author LNL
 * @date 2021/5/19 14:48
 */
@Controller
@Api(tags = "请求处理文件")
public class RequestImgController {

    @Autowired
    private ImgMapper imgMapper;

    @GetMapping("/fileResource/{id}")
    public void requestImg(HttpServletResponse response,
                           @PathVariable("id") String id) {
        try {
            //通过id获取文件资源
            Img img = imgMapper.selectByPrimaryKey(id);
            //获取到文件的后缀名
            OutputStream os = response.getOutputStream();
            File file = new File(img.getPath());
            FileInputStream is = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer,0,len);
            }
            os.flush();
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
